package com.dm.cloud.controller.base;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author huyanchao
 */
@AllArgsConstructor
public class BaseExcelController {

    public String getInvalidImportMessage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            return "请上传文件!";
        }
        String suffix = ".xls";
        String suffix1 = ".xlsx";
        if ((!StringUtils.endsWithIgnoreCase(filename, suffix) && !StringUtils.endsWithIgnoreCase(filename, suffix1))) {
            return "导入文件不是excel文件类型!";
        }
        return null;
    }

    public OutputStream exportTemplateStream(List<?> list) throws IOException {

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ExcelWriter excelWriter = EasyExcel.write().file(os).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        excelWriter.write(list, writeSheet);
        //一定要进行关闭 才能获取os
        excelWriter.finish();
        OutputStream outputStream =  excelWriter.writeContext().writeWorkbookHolder().getOutputStream();

        return outputStream;
    }

    public void exportTemplate(HttpServletResponse response, String name, Class<?> excelClass, List<?> list, boolean enableLog) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        String fileName = URLEncoder.encode(name, StandardCharsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), excelClass).sheet(name).doWrite(list);
    }

    public void importExcel(MultipartFile file, Class<?> excelClass, AnalysisEventListener<?> importListener, String title) {

        String invalidMessage = getInvalidImportMessage(file);
        if (invalidMessage != null) {
            throw new RuntimeException(invalidMessage);
        }
        InputStream inputStream;
        try {
            inputStream = new BufferedInputStream(file.getInputStream());
            ExcelReaderBuilder builder = EasyExcel.read(inputStream, excelClass, importListener);
            builder.doReadAll();
        } catch (Exception e) {
            throw new RuntimeException("数据格式错误");
        }
    }
}
